<template>
  <div class="message-push">
    <!-- 面包屑导航 -->
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item :to="{ path: '/dashboard' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>消息通知</el-breadcrumb-item>
      <el-breadcrumb-item>消息推送</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- WebSocket连接状态指示器 -->
    <div class="ws-status-indicator">
      <el-tooltip :content="wsConnected ? '实时推送已连接' : '实时推送连接已断开'" placement="bottom">
        <div :class="['status-dot', wsConnected ? 'connected' : 'disconnected']">
          <span class="status-text">{{ wsConnected ? '实时推送' : '推送断开' }}</span>
        </div>
      </el-tooltip>
    </div>

    <!-- 统计信息卡片 -->
    <el-row :gutter="20" class="statistics-cards">
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background-color: #409eff;">
              <el-icon><Promotion /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statistics.totalPushed || 0 }}</div>
              <div class="stat-label">今日推送</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background-color: #67c23a;">
              <el-icon><SuccessFilled /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statistics.successPushed || 0 }}</div>
              <div class="stat-label">推送成功</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background-color: #e6a23c;">
              <el-icon><Clock /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statistics.scheduledPushed || 0 }}</div>
              <div class="stat-label">定时推送</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card">
          <div class="stat-item">
            <div class="stat-icon" style="background-color: #f56c6c;">
              <el-icon><WarningFilled /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-value">{{ statistics.failedPushed || 0 }}</div>
              <div class="stat-label">推送失败</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 主要内容区域 -->
    <el-row :gutter="20" class="main-content">
      <!-- 左侧推送表单区域 -->
      <el-col :span="16">
        <el-card class="push-form-card">
          <template #header>
            <div class="card-header">
              <span>消息推送表单</span>
              <el-button-group>
                <el-button size="small" icon="DocumentCopy" @click="showTemplateDialog">
                  模板管理
                </el-button>
                <el-button size="small" icon="View" @click="showPreviewDialog">
                  预览消息
                </el-button>
              </el-button-group>
            </div>
          </template>

          <el-form
            :model="pushForm"
            :rules="pushFormRules"
            ref="pushFormRef"
            label-width="100px"
          >
            <el-form-item label="消息标题" prop="title">
              <el-input
                v-model="pushForm.title"
                placeholder="请输入消息标题"
                show-word-limit
                maxlength="100"
              />
            </el-form-item>

            <el-form-item label="消息类型" prop="messageType">
              <el-select v-model="pushForm.messageType" placeholder="请选择消息类型" style="width: 100%">
                <el-option label="系统通知" value="system" />
                <el-option label="赛事公告" value="sports" />
                <el-option label="成绩通知" value="score" />
                <el-option label="赛程提醒" value="schedule" />
                <el-option label="紧急通知" value="urgent" />
              </el-select>
            </el-form-item>

            <el-form-item label="消息内容" prop="content">
              <el-input
                v-model="pushForm.content"
                type="textarea"
                :rows="6"
                placeholder="请输入消息内容"
                show-word-limit
                maxlength="1000"
              />
            </el-form-item>

            <el-form-item label="优先级" prop="priority">
              <el-radio-group v-model="pushForm.priority">
                <el-radio label="low">低</el-radio>
                <el-radio label="medium">中</el-radio>
                <el-radio label="high">高</el-radio>
                <el-radio label="urgent">紧急</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="推送方式" prop="pushType">
              <el-checkbox-group v-model="pushForm.pushType">
                <el-checkbox label="app">APP推送</el-checkbox>
                <el-checkbox label="sms">短信通知</el-checkbox>
                <el-checkbox label="email">邮件通知</el-checkbox>
                <el-checkbox label="wechat">微信通知</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="定时推送">
              <el-switch
                v-model="pushForm.isScheduled"
                active-text="开启"
                inactive-text="关闭"
              />
            </el-form-item>

            <el-form-item
              v-if="pushForm.isScheduled"
              label="推送时间"
              prop="scheduledTime"
            >
              <el-date-picker
                v-model="pushForm.scheduledTime"
                type="datetime"
                placeholder="选择推送时间"
                style="width: 100%"
                :disabled-date="disabledDate"
              />
            </el-form-item>

            <el-form-item>
              <el-button
                type="primary"
                @click="handlePushMessage"
                :loading="pushing"
                :disabled="selectedRecipients.length === 0"
              >
                <el-icon><Promotion /></el-icon>
                {{ pushForm.isScheduled ? '定时推送' : '立即推送' }}
              </el-button>
              <el-button @click="resetPushForm">
                <el-icon><Refresh /></el-icon>
                重置表单
              </el-button>
              <el-button type="success" @click="testPush">
                <el-icon><Cpu /></el-icon>
                测试推送
              </el-button>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>

      <!-- 右侧接收者选择区域 -->
      <el-col :span="8">
        <el-card class="recipient-card">
          <template #header>
            <div class="card-header">
              <span>接收者选择 ({{ selectedRecipients.length }}人)</span>
              <el-button size="small" icon="Refresh" @click="refreshRecipients">
                刷新
              </el-button>
            </div>
          </template>

          <el-tabs v-model="activeRecipientTab" @tab-click="handleTabClick">
            <el-tab-pane label="按角色" name="role">
              <div class="role-selection">
                <el-checkbox
                  :indeterminate="isIndeterminateRole"
                  v-model="checkAllRole"
                  @change="handleCheckAllRole"
                >
                  全选角色
                </el-checkbox>
                <el-divider />
                <el-checkbox-group
                  v-model="selectedRoles"
                  @change="handleRoleChange"
                >
                  <div v-for="role in roleList" :key="role.value" class="role-item">
                    <el-checkbox :label="role.value">
                      <div class="role-info">
                        <span class="role-name">{{ role.label }}</span>
                        <span class="role-count">({{ role.count }}人)</span>
                      </div>
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
              </div>
            </el-tab-pane>

            <el-tab-pane label="按用户" name="user">
              <div class="user-selection">
                <div class="search-user">
                  <el-input
                    v-model="userSearchKeyword"
                    placeholder="搜索用户"
                    prefix-icon="Search"
                    clearable
                    @input="handleUserSearch"
                  />
                </div>
                <el-divider />
                <el-checkbox
                  :indeterminate="isIndeterminateUser"
                  v-model="checkAllUser"
                  @change="handleCheckAllUser"
                >
                  全选用户
                </el-checkbox>
                <div class="user-list">
                  <el-checkbox-group
                    v-model="selectedUsers"
                    @change="handleUserChange"
                  >
                    <div v-for="user in filteredUserList" :key="user.id" class="user-item">
                      <el-checkbox :label="user.id">
                        <div class="user-info">
                          <el-avatar :size="30" :src="user.avatar">{{ user.name.charAt(0) }}</el-avatar>
                          <div class="user-details">
                            <div class="user-name">{{ user.name }}</div>
                            <div class="user-role">{{ user.roleName }}</div>
                          </div>
                        </div>
                      </el-checkbox>
                    </div>
                  </el-checkbox-group>
                </div>
              </div>
            </el-tab-pane>

            <el-tab-pane label="按部门" name="department">
              <div class="department-selection">
                <el-checkbox
                  :indeterminate="isIndeterminateDept"
                  v-model="checkAllDept"
                  @change="handleCheckAllDept"
                >
                  全选部门
                </el-checkbox>
                <el-divider />
                <el-checkbox-group
                  v-model="selectedDepartments"
                  @change="handleDepartmentChange"
                >
                  <div v-for="dept in departmentList" :key="dept.value" class="dept-item">
                    <el-checkbox :label="dept.value">
                      <div class="dept-info">
                        <span class="dept-name">{{ dept.label }}</span>
                        <span class="dept-count">({{ dept.count }}人)</span>
                      </div>
                    </el-checkbox>
                  </div>
                </el-checkbox-group>
              </div>
            </el-tab-pane>
          </el-tabs>

          <!-- 已选择的接收者预览 -->
          <div class="selected-recipients" v-if="selectedRecipients.length > 0">
            <el-divider content-position="left">已选择接收者</el-divider>
            <el-tag
              v-for="recipient in selectedRecipients.slice(0, 5)"
              :key="recipient.id"
              closable
              @close="removeRecipient(recipient)"
              class="recipient-tag"
            >
              {{ recipient.name }}
            </el-tag>
            <el-tag
              v-if="selectedRecipients.length > 5"
              type="info"
              class="recipient-tag"
            >
              +{{ selectedRecipients.length - 5 }}人
            </el-tag>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 底部推送历史区域 -->
    <el-card class="history-card">
      <template #header>
        <div class="card-header">
          <span>推送历史记录</span>
          <div class="header-actions">
            <el-button-group>
              <el-button size="small" icon="Download" @click="exportHistory">
                导出记录
              </el-button>
              <el-button size="small" icon="Refresh" @click="loadPushHistory">
                刷新
              </el-button>
            </el-button-group>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="history-search">
        <el-form :inline="true" :model="historySearchForm" ref="historySearchFormRef">
          <el-form-item label="消息标题" prop="title">
            <el-input
              v-model="historySearchForm.title"
              placeholder="请输入消息标题"
              clearable
              style="width: 200px;"
            />
          </el-form-item>
          <el-form-item label="推送状态" prop="status">
            <el-select
              v-model="historySearchForm.status"
              placeholder="请选择推送状态"
              clearable
              style="width: 150px;"
            >
              <el-option label="推送成功" value="success" />
              <el-option label="推送失败" value="failed" />
              <el-option label="等待推送" value="pending" />
              <el-option label="已取消" value="cancelled" />
            </el-select>
          </el-form-item>
          <el-form-item label="推送时间" prop="dateRange">
            <el-date-picker
              v-model="historySearchForm.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              style="width: 240px;"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="searchHistory">
              搜索
            </el-button>
            <el-button icon="Refresh" @click="resetHistorySearch">
              重置
            </el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 历史记录表格 -->
      <el-table
        v-loading="historyLoading"
        :data="pushHistoryList"
        stripe
        style="width: 100%"
      >
        <el-table-column type="index" label="#" width="60" />
        <el-table-column prop="title" label="消息标题" min-width="200" show-overflow-tooltip />
        <el-table-column prop="messageType" label="消息类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getMessageTypeTagType(row.messageType)">
              {{ getMessageTypeLabel(row.messageType) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="recipientCount" label="接收人数" width="100" />
        <el-table-column prop="pushType" label="推送方式" width="150">
          <template #default="{ row }">
            <el-tag v-for="type in row.pushType" :key="type" size="small" class="push-type-tag">
              {{ getPushTypeLabel(type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="推送状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getPushStatusTagType(row.status)">
              {{ getPushStatusLabel(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="scheduledTime" label="推送时间" width="180" />
        <el-table-column prop="createdBy" label="操作人" width="100" />
        <el-table-column label="操作" width="180" fixed="right">
          <template #default="{ row }">
            <el-button
              type="primary"
              size="small"
              icon="View"
              @click="viewPushDetail(row)"
            >
              查看
            </el-button>
            <el-button
              v-if="row.status === 'pending'"
              type="danger"
              size="small"
              icon="Close"
              @click="cancelPush(row)"
            >
              取消
            </el-button>
            <el-button
              v-if="row.status === 'failed'"
              type="warning"
              size="small"
              icon="Refresh"
              @click="retryPush(row)"
            >
              重试
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="historyPagination.currentPage"
          v-model:page-size="historyPagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="historyPagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleHistorySizeChange"
          @current-change="handleHistoryCurrentChange"
        />
      </div>
    </el-card>

    <!-- 消息预览对话框 -->
    <el-dialog
      v-model="previewDialogVisible"
      title="消息预览"
      width="600px"
    >
      <div class="message-preview">
        <div class="preview-header">
          <h3>{{ pushForm.title || '消息标题' }}</h3>
          <div class="preview-meta">
            <el-tag :type="getMessageTypeTagType(pushForm.messageType)">
              {{ getMessageTypeLabel(pushForm.messageType) }}
            </el-tag>
            <el-tag :type="getPriorityTagType(pushForm.priority)" size="small">
              {{ getPriorityLabel(pushForm.priority) }}
            </el-tag>
            <span class="preview-time">{{ formatTime(new Date()) }}</span>
          </div>
        </div>
        <el-divider />
        <div class="preview-content">
          {{ pushForm.content || '消息内容' }}
        </div>
        <el-divider />
        <div class="preview-recipients">
          <h4>接收者 ({{ selectedRecipients.length }}人)</h4>
          <div class="recipient-list">
            <el-tag
              v-for="recipient in selectedRecipients.slice(0, 10)"
              :key="recipient.id"
              size="small"
              class="preview-recipient-tag"
            >
              {{ recipient.name }}
            </el-tag>
            <span v-if="selectedRecipients.length > 10" class="more-recipients">
              等{{ selectedRecipients.length }}人
            </span>
          </div>
        </div>
        <div class="preview-push-types">
          <h4>推送方式</h4>
          <el-tag
            v-for="type in pushForm.pushType"
            :key="type"
            size="small"
            class="preview-push-type-tag"
          >
            {{ getPushTypeLabel(type) }}
          </el-tag>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="previewDialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="handlePushMessage" :loading="pushing">
            确认推送
          </el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 模板管理对话框 -->
    <el-dialog
      v-model="templateDialogVisible"
      title="消息模板管理"
      width="800px"
    >
      <div class="template-management">
        <div class="template-actions">
          <el-button type="primary" icon="Plus" @click="showAddTemplateDialog">
            新增模板
          </el-button>
          <el-button
            type="danger"
            icon="Delete"
            :disabled="!selectedTemplates.length"
            @click="batchDeleteTemplates"
          >
            批量删除
          </el-button>
        </div>
        <el-table
          v-loading="templateLoading"
          :data="templateList"
          @selection-change="handleTemplateSelection"
          stripe
          style="width: 100%"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column type="index" label="#" width="60" />
          <el-table-column prop="templateName" label="模板名称" width="150" />
          <el-table-column prop="messageType" label="消息类型" width="120">
            <template #default="{ row }">
              <el-tag :type="getMessageTypeTagType(row.messageType)" size="small">
                {{ getMessageTypeLabel(row.messageType) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="title" label="标题" min-width="200" show-overflow-tooltip />
          <el-table-column prop="content" label="内容" min-width="200" show-overflow-tooltip />
          <el-table-column prop="priority" label="优先级" width="100">
            <template #default="{ row }">
              <el-tag :type="getPriorityTagType(row.priority)" size="small">
                {{ getPriorityLabel(row.priority) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="180">
            <template #default="{ row }">
              <el-button
                type="primary"
                size="small"
                icon="DocumentCopy"
                @click="applyTemplate(row)"
              >
                应用
              </el-button>
              <el-button
                type="warning"
                size="small"
                icon="Edit"
                @click="editTemplate"
              >
                编辑
              </el-button>
              <el-button
                type="danger"
                size="small"
                icon="Delete"
                @click="deleteTemplate(row)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="templateDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 推送详情对话框 -->
    <el-dialog
      v-model="pushDetailDialogVisible"
      title="推送详情"
      width="700px"
    >
      <div class="push-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="消息标题">{{ currentPushDetail.title }}</el-descriptions-item>
          <el-descriptions-item label="消息类型">
            <el-tag :type="getMessageTypeTagType(currentPushDetail.messageType)">
              {{ getMessageTypeLabel(currentPushDetail.messageType) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="接收人数">{{ currentPushDetail.recipientCount }}</el-descriptions-item>
          <el-descriptions-item label="推送状态">
            <el-tag :type="getPushStatusTagType(currentPushDetail.status)">
              {{ getPushStatusLabel(currentPushDetail.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="推送方式">
            <div class="push-types-detail">
              <el-tag
                v-for="type in currentPushDetail.pushType"
                :key="type"
                size="small"
                class="push-type-tag"
              >
                {{ getPushTypeLabel(type) }}
              </el-tag>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="优先级">
            <el-tag :type="getPriorityTagType(currentPushDetail.priority)" size="small">
              {{ getPriorityLabel(currentPushDetail.priority) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ currentPushDetail.createAt }}</el-descriptions-item>
          <el-descriptions-item label="推送时间">{{ currentPushDetail.pushTime || '未推送' }}</el-descriptions-item>
          <el-descriptions-item label="操作人">{{ currentPushDetail.createdBy }}</el-descriptions-item>
          <el-descriptions-item label="消息内容" :span="2">
            <div class="push-content">{{ currentPushDetail.content }}</div>
          </el-descriptions-item>
          <el-descriptions-item v-if="currentPushDetail.failureReason" label="失败原因" :span="2">
            <div class="failure-reason">{{ currentPushDetail.failureReason }}</div>
          </el-descriptions-item>
        </el-descriptions>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="pushDetailDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, reactive, onMounted, computed, watch, onBeforeUnmount } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import {
  pushSingleMessage,
  batchPushMessages,
  testPushMessage,
  getAdminMessageStatistics
} from '@/api/message'

export default {
  name: 'MessagePush',
  setup() {
    // 响应式数据
    const pushing = ref(false)
    const historyLoading = ref(false)
    const templateLoading = ref(false)
    const pushHistoryList = ref([])
    const templateList = ref([])
    const selectedTemplates = ref([])
    const currentPushDetail = ref({})

    // WebSocket 实例
    const websocket = ref(null)
    const wsConnected = ref(false)
    const wsReconnectAttempts = ref(0)
    const wsMaxReconnectAttempts = ref(5)
    const wsReconnectInterval = ref(5000)
    const heartbeatTimer = ref(null)

    // 统计数据
    const statistics = reactive({
      totalPushed: 0,
      successPushed: 0,
      scheduledPushed: 0,
      failedPushed: 0
    })

    // 推送表单
    const pushForm = reactive({
      title: '',
      messageType: 'system',
      content: '',
      priority: 'medium',
      pushType: ['app'],
      isScheduled: false,
      scheduledTime: null
    })

    // 接收者相关
    const activeRecipientTab = ref('role')
    const selectedRoles = ref([])
    const selectedUsers = ref([])
    const selectedDepartments = ref([])
    const selectedRecipients = ref([])
    const userSearchKeyword = ref('')

    // 角色列表
    const roleList = ref([
      { label: '管理员', value: 'admin', count: 5 },
      { label: '老师', value: 'teacher', count: 50 },
      { label: '学生', value: 'student', count: 500 },
      { label: '裁判', value: 'referee', count: 20 },
      { label: '志愿者', value: 'volunteer', count: 100 }
    ])

    // 用户列表
    const userList = ref([
      { id: 1, name: '张三', roleName: '管理员', avatar: '' },
      { id: 2, name: '李四', roleName: '老师', avatar: '' },
      { id: 3, name: '王五', roleName: '学生', avatar: '' },
      { id: 4, name: '赵六', roleName: '裁判', avatar: '' },
      { id: 5, name: '陈七', roleName: '志愿者', avatar: '' },
      { id: 6, name: '刘八', roleName: '学生', avatar: '' },
      { id: 7, name: '周九', roleName: '老师', avatar: '' },
      { id: 8, name: '吴十', roleName: '学生', avatar: '' }
    ])

    // 部门列表
    const departmentList = ref([
      { label: '教务处', value: 'academic', count: 20 },
      { label: '体育部', value: 'sports', count: 15 },
      { label: '学生会', value: 'student_union', count: 50 },
      { label: '各学院', value: 'colleges', count: 300 },
      { label: '后勤处', value: 'logistics', count: 30 }
    ])

    // 历史记录相关
    const historyPagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })

    const historySearchForm = reactive({
      title: '',
      status: '',
      dateRange: null
    })

    // 对话框显示状态
    const previewDialogVisible = ref(false)
    const templateDialogVisible = ref(false)
    const pushDetailDialogVisible = ref(false)

    // 表单引用
    const pushFormRef = ref(null)
    const historySearchFormRef = ref(null)

    // 表单验证规则
    const pushFormRules = {
      title: [
        { required: true, message: '请输入消息标题', trigger: 'blur' },
        { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
      ],
      messageType: [
        { required: true, message: '请选择消息类型', trigger: 'change' }
      ],
      content: [
        { required: true, message: '请输入消息内容', trigger: 'blur' },
        { min: 5, max: 1000, message: '内容长度在 5 到 1000 个字符', trigger: 'blur' }
      ],
      pushType: [
        { required: true, message: '请选择至少一种推送方式', trigger: 'change' }
      ],
      priority: [
        { required: true, message: '请选择优先级', trigger: 'change' }
      ],
      scheduledTime: [
        { required: true, message: '请选择推送时间', trigger: 'change' }
      ]
    }

    // 计算属性
    const checkAllRole = computed({
      get: () => selectedRoles.value.length === roleList.value.length,
      set: (value) => {
        if (value) {
          selectedRoles.value = roleList.value.map(role => role.value)
        } else {
          selectedRoles.value = []
        }
        updateSelectedRecipients()
      }
    })

    const isIndeterminateRole = computed(() => {
      return selectedRoles.value.length > 0 && selectedRoles.value.length < roleList.value.length
    })

    const checkAllUser = computed({
      get: () => selectedUsers.value.length === filteredUserList.value.length,
      set: (value) => {
        if (value) {
          selectedUsers.value = filteredUserList.value.map(user => user.id)
        } else {
          selectedUsers.value = []
        }
        updateSelectedRecipients()
      }
    })

    const isIndeterminateUser = computed(() => {
      return selectedUsers.value.length > 0 && selectedUsers.value.length < filteredUserList.value.length
    })

    const checkAllDept = computed({
      get: () => selectedDepartments.value.length === departmentList.value.length,
      set: (value) => {
        if (value) {
          selectedDepartments.value = departmentList.value.map(dept => dept.value)
        } else {
          selectedDepartments.value = []
        }
        updateSelectedRecipients()
      }
    })

    const isIndeterminateDept = computed(() => {
      return selectedDepartments.value.length > 0 && selectedDepartments.value.length < departmentList.value.length
    })

    const filteredUserList = computed(() => {
      if (!userSearchKeyword.value) {
        return userList.value
      }
      return userList.value.filter(user =>
        user.name.toLowerCase().includes(userSearchKeyword.value.toLowerCase())
      )
    })

    // 生命周期钩子
    onMounted(() => {
      loadStatistics()
      loadPushHistory()
      loadTemplates()
      initWebSocket()
    })

    onBeforeUnmount(() => {
      closeWebSocket()
    })

    // 监听器
    watch([selectedRoles, selectedUsers, selectedDepartments], () => {
      updateSelectedRecipients()
    })

    // WebSocket 相关方法
    const initWebSocket = () => {
      // 根据当前环境获取WebSocket地址
      const protocol = window.location.protocol === 'https:' ? 'wss:' : 'ws:'
      const wsUrl = `${protocol}//${window.location.host}/websocket/admin-push`

      try {
        websocket.value = new WebSocket(wsUrl)
        setupWebSocketEvents()
      } catch (error) {
        console.error('WebSocket连接失败:', error)
        ElMessage.error('实时推送连接失败，将使用定时刷新')
        setupFallbackPolling()
      }
    }

    const setupWebSocketEvents = () => {
      if (!websocket.value) return

      websocket.value.onopen = () => {
        console.log('WebSocket连接成功')
        wsConnected.value = true
        wsReconnectAttempts.value = 0
        startHeartbeat()
        ElMessage.success('实时推送已连接')
      }

      websocket.value.onmessage = (event) => {
        handleWebSocketMessage(event)
      }

      websocket.value.onclose = () => {
        console.log('WebSocket连接关闭')
        wsConnected.value = false
        stopHeartbeat()
        handleWebSocketDisconnect()
      }

      websocket.value.onerror = (error) => {
        console.error('WebSocket错误:', error)
        wsConnected.value = false
        ElMessage.warning('实时推送连接异常')
      }
    }

    const handleWebSocketMessage = (event) => {
      try {
        const data = JSON.parse(event.data)

        switch (data.type) {
          case 'push_status_update':
            handlePushStatusUpdate(data.payload)
            break
          case 'push_statistics':
            handlePushStatistics(data.payload)
            break
          case 'heartbeat':
            handleHeartbeatResponse()
            break
          default:
            console.log('未知消息类型:', data.type)
        }
      } catch (error) {
        console.error('处理WebSocket消息失败:', error)
      }
    }

    const handlePushStatusUpdate = (data) => {
      // 更新推送历史中的状态
      const pushItem = pushHistoryList.value.find(item => item.id === data.pushId)
      if (pushItem) {
        pushItem.status = data.status
        if (data.pushTime) {
          pushItem.pushTime = data.pushTime
        }
        if (data.failureReason) {
          pushItem.failureReason = data.failureReason
        }
      }

      // 显示通知
      ElNotification({
        title: '推送状态更新',
        message: `消息"${data.title}"推送状态已更新为: ${getPushStatusLabel(data.status)}`,
        type: data.status === 'success' ? 'success' : data.status === 'failed' ? 'error' : 'warning',
        duration: 5000
      })

      // 更新统计数据
      loadStatistics()
    }

    const handlePushStatistics = (data) => {
      // 更新统计数据
      Object.assign(statistics, data)
    }

    const startHeartbeat = () => {
      stopHeartbeat()
      heartbeatTimer.value = setInterval(() => {
        if (websocket.value && wsConnected.value) {
          websocket.value.send(JSON.stringify({ type: 'heartbeat' }))
        }
      }, 30000)
    }

    const stopHeartbeat = () => {
      if (heartbeatTimer.value) {
        clearInterval(heartbeatTimer.value)
        heartbeatTimer.value = null
      }
    }

    const handleHeartbeatResponse = () => {
      console.log('WebSocket心跳正常')
    }

    const handleWebSocketDisconnect = () => {
      // 尝试重连
      if (wsReconnectAttempts.value < wsMaxReconnectAttempts.value) {
        wsReconnectAttempts.value++
        console.log(`WebSocket重连尝试 ${wsReconnectAttempts.value}/${wsMaxReconnectAttempts.value}`)

        setTimeout(() => {
          ElMessage.info(`正在尝试重连(${wsReconnectAttempts.value}/${wsMaxReconnectAttempts.value})...`)
          initWebSocket()
        }, wsReconnectInterval.value)
      } else {
        ElMessage.error('实时推送连接失败，已达到最大重连次数，将使用定时刷新')
        setupFallbackPolling()
      }
    }

    const setupFallbackPolling = () => {
      setInterval(() => {
        if (!wsConnected.value) {
          loadStatistics()
          loadPushHistory()
        }
      }, 30000)
    }

    const closeWebSocket = () => {
      stopHeartbeat()

      if (websocket.value) {
        websocket.value.close()
        websocket.value = null
      }
      wsConnected.value = false
    }

    // 方法
    const loadStatistics = async () => {
      try {
        const response = await getAdminMessageStatistics()
        if (response.code === 200) {
          // 这里假设API返回的是推送统计数据，实际情况可能需要调整
          Object.assign(statistics, response.data)
        }
      } catch (error) {
        console.error('加载统计数据失败:', error)
      }
    }

    const loadPushHistory = async () => {
      historyLoading.value = true
      try {
        // 这里使用模拟数据，实际应该调用API
        const mockData = [
          {
            id: 1,
            title: '运动会开幕式通知',
            messageType: 'sports',
            content: '请各位师生准时参加明天上午9点的运动会开幕式...',
            recipientCount: 500,
            pushType: ['app', 'sms'],
            status: 'success',
            priority: 'high',
            scheduledTime: '2023-10-12 09:00:00',
            createdBy: '张管理员',
            createAt: '2023-10-11 14:30:00',
            pushTime: '2023-10-12 09:00:00'
          },
          {
            id: 2,
            title: '成绩查询系统维护通知',
            messageType: 'system',
            content: '成绩查询系统将于今晚22:00-24:00进行维护...',
            recipientCount: 200,
            pushType: ['app', 'email'],
            status: 'success',
            priority: 'medium',
            scheduledTime: '2023-10-11 22:00:00',
            createdBy: '李管理员',
            createAt: '2023-10-11 16:20:00',
            pushTime: '2023-10-11 22:00:00'
          },
          {
            id: 3,
            title: '篮球比赛延期通知',
            messageType: 'schedule',
            content: '因天气原因，原定于今天下午的篮球比赛延期至明天...',
            recipientCount: 50,
            pushType: ['app', 'sms', 'wechat'],
            status: 'failed',
            priority: 'urgent',
            scheduledTime: '2023-10-11 15:00:00',
            createdBy: '王管理员',
            createAt: '2023-10-11 14:00:00',
            failureReason: '短信网关故障'
          }
        ]

        pushHistoryList.value = mockData
        historyPagination.total = mockData.length
      } catch (error) {
        console.error('加载推送历史失败:', error)
        ElMessage.error('加载推送历史失败')
      } finally {
        historyLoading.value = false
      }
    }

    const loadTemplates = async () => {
      templateLoading.value = true
      try {
        // 这里使用模拟数据，实际应该调用API
        const mockTemplates = [
          {
            id: 1,
            templateName: '比赛通知模板',
            messageType: 'sports',
            title: '【比赛通知】{比赛名称}',
            content: '各位师生：\n\n{比赛名称}将于{比赛时间}在{比赛地点}举行，请相关人员准时参加。\n\n特此通知！',
            priority: 'high'
          },
          {
            id: 2,
            templateName: '系统维护通知模板',
            messageType: 'system',
            title: '【系统维护】{系统名称}',
            content: '各位用户：\n\n{系统名称}将于{维护时间}进行系统维护，预计维护时长{维护时长}。\n\n维护期间系统将无法正常使用，请提前做好准备。\n\n给您带来的不便，敬请谅解！',
            priority: 'medium'
          }
        ]

        templateList.value = mockTemplates
      } catch (error) {
        console.error('加载模板失败:', error)
        ElMessage.error('加载模板失败')
      } finally {
        templateLoading.value = false
      }
    }

    const updateSelectedRecipients = () => {
      selectedRecipients.value = []

      // 添加选中角色的用户
      selectedRoles.value.forEach(roleValue => {
        const role = roleList.value.find(r => r.value === roleValue)
        if (role) {
          // 这里应该根据角色获取实际用户列表，简化处理
          for (let i = 0; i < Math.min(role.count, 3); i++) {
            selectedRecipients.value.push({
              id: `${roleValue}_${i}`,
              name: `${role.label}${i + 1}`,
              type: 'role',
              typeId: roleValue
            })
          }
        }
      })

      // 添加选中的用户
      selectedUsers.value.forEach(userId => {
        const user = userList.value.find(u => u.id === userId)
        if (user) {
          selectedRecipients.value.push({
            id: user.id,
            name: user.name,
            type: 'user'
          })
        }
      })

      // 添加选中部门的用户
      selectedDepartments.value.forEach(deptValue => {
        const dept = departmentList.value.find(d => d.value === deptValue)
        if (dept) {
          // 这里应该根据部门获取实际用户列表，简化处理
          for (let i = 0; i < Math.min(dept.count, 3); i++) {
            selectedRecipients.value.push({
              id: `${deptValue}_${i}`,
              name: `${dept.label}用户${i + 1}`,
              type: 'department',
              typeId: deptValue
            })
          }
        }
      })

      // 去重
      const uniqueRecipients = []
      const seenIds = new Set()
      selectedRecipients.value.forEach(recipient => {
        if (!seenIds.has(recipient.id)) {
          seenIds.add(recipient.id)
          uniqueRecipients.push(recipient)
        }
      })
      selectedRecipients.value = uniqueRecipients
    }

    const handleCheckAllRole = () => {
      // 计算属性会处理
    }

    const handleCheckAllUser = () => {
      // 计算属性会处理
    }

    const handleCheckAllDept = () => {
      // 计算属性会处理
    }

    const handleRoleChange = () => {
      updateSelectedRecipients()
    }

    const handleUserChange = () => {
      updateSelectedRecipients()
    }

    const handleDepartmentChange = () => {
      updateSelectedRecipients()
    }

    const handleTabClick = () => {
      // 切换标签页时的处理
    }

    const handleUserSearch = () => {
      // 用户搜索功能由计算属性自动处理
    }

    const refreshRecipients = () => {
      // 刷新接收者列表
      ElMessage.success('接收者列表已刷新')
    }

    const removeRecipient = (recipient) => {
      if (recipient.type === 'user') {
        selectedUsers.value = selectedUsers.value.filter(id => id !== recipient.id)
      } else if (recipient.type === 'role') {
        selectedRoles.value = selectedRoles.value.filter(value => value !== recipient.typeId)
      } else if (recipient.type === 'department') {
        selectedDepartments.value = selectedDepartments.value.filter(value => value !== recipient.typeId)
      }
      updateSelectedRecipients()
    }

    const handlePushMessage = async () => {
      try {
        await pushFormRef.value.validate()

        if (selectedRecipients.value.length === 0) {
          ElMessage.warning('请选择至少一个接收者')
          return
        }

        pushing.value = true

        const pushData = {
          title: pushForm.title,
          content: pushForm.content,
          messageType: pushForm.messageType,
          priority: pushForm.priority,
          pushType: pushForm.pushType,
          recipients: selectedRecipients.value.map(r => r.id)
        }

        if (pushForm.isScheduled) {
          pushData.scheduledTime = pushForm.scheduledTime
        }

        let response
        if (selectedRecipients.value.length === 1) {
          response = await pushSingleMessage(pushData)
        } else {
          response = await batchPushMessages(pushData)
        }

        if (response.code === 200) {
          ElMessage.success(pushForm.isScheduled ? '定时推送设置成功' : '消息推送成功')
          resetPushForm()
          previewDialogVisible.value = false
          loadPushHistory()
          loadStatistics()
        } else {
          ElMessage.error(response.message || '推送失败')
        }
      } catch (error) {
        console.error('推送消息失败:', error)
        ElMessage.error('推送消息失败')
      } finally {
        pushing.value = false
      }
    }

    const resetPushForm = () => {
      Object.assign(pushForm, {
        title: '',
        messageType: 'system',
        content: '',
        priority: 'medium',
        pushType: ['app'],
        isScheduled: false,
        scheduledTime: null
      })
      pushFormRef.value?.resetFields()
    }

    const testPush = async () => {
      try {
        await pushFormRef.value.validate()

        const testData = {
          title: `[测试] ${pushForm.title}`,
          content: pushForm.content,
          messageType: pushForm.messageType,
          priority: pushForm.priority,
          pushType: pushForm.pushType
        }

        const response = await testPushMessage(testData)
        if (response.code === 200) {
          ElMessage.success('测试推送成功')
        } else {
          ElMessage.error(response.message || '测试推送失败')
        }
      } catch (error) {
        console.error('测试推送失败:', error)
        ElMessage.error('测试推送失败')
      }
    }

    const showPreviewDialog = () => {
      if (selectedRecipients.value.length === 0) {
        ElMessage.warning('请先选择接收者')
        return
      }
      previewDialogVisible.value = true
    }

    const showTemplateDialog = () => {
      templateDialogVisible.value = true
      loadTemplates()
    }

    const handleTemplateSelection = (selection) => {
      selectedTemplates.value = selection
    }

    const applyTemplate = (template) => {
      pushForm.title = template.title
      pushForm.content = template.content
      pushForm.messageType = template.messageType
      pushForm.priority = template.priority
      templateDialogVisible.value = false
      ElMessage.success('模板应用成功')
    }

    const editTemplate = () => {
      // 编辑模板功能
      ElMessage.info('编辑模板功能开发中...')
    }

    const deleteTemplate = (template) => {
      ElMessageBox.confirm(
        `确定要删除模板"${template.templateName}"吗？`,
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          // 这里应该调用删除模板API
          // 暂时模拟删除成功
          ElMessage.success('删除成功')
          loadTemplates()
        } catch (error) {
          console.error('删除模板失败:', error)
          ElMessage.error('删除模板失败')
        }
      })
    }

    const batchDeleteTemplates = () => {
      if (!selectedTemplates.value.length) {
        ElMessage.warning('请选择要删除的模板')
        return
      }

      ElMessageBox.confirm(
        `确定要删除选中的 ${selectedTemplates.value.length} 个模板吗？`,
        '确认批量删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(async () => {
        try {
          // 这里应该调用批量删除API
          ElMessage.success('批量删除成功')
          selectedTemplates.value = []
          loadTemplates()
        } catch (error) {
          console.error('批量删除失败:', error)
          ElMessage.error('批量删除失败')
        }
      })
    }

    const showAddTemplateDialog = () => {
      // 新增模板功能
      ElMessage.info('新增模板功能开发中...')
    }

    const searchHistory = () => {
      historyPagination.currentPage = 1
      loadPushHistory()
    }

    const resetHistorySearch = () => {
      historySearchFormRef.value?.resetFields()
      searchHistory()
    }

    const handleHistorySizeChange = () => {
      loadPushHistory()
    }

    const handleHistoryCurrentChange = () => {
      loadPushHistory()
    }

    const viewPushDetail = (pushData) => {
      currentPushDetail.value = { ...pushData }
      pushDetailDialogVisible.value = true
    }

    const cancelPush = (pushData) => {
      ElMessageBox.confirm(
        `确定要取消推送"${pushData.title}"吗？`,
        '确认取消',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 调用取消推送API
        ElMessage.success('推送已取消')
        loadPushHistory()
      })
    }

    const retryPush = (pushData) => {
      ElMessageBox.confirm(
        `确定要重新推送"${pushData.title}"吗？`,
        '确认重试',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).then(() => {
        // 调用重试推送API
        ElMessage.success('重新推送成功')
        loadPushHistory()
      })
    }

    const exportHistory = () => {
      // 导出历史记录
      ElMessage.info('导出功能开发中...')
    }

    const disabledDate = (time) => {
      return time.getTime() < Date.now() - 8.64e7 // 不能选择今天之前的日期
    }

    const formatTime = (date) => {
      return date.toLocaleString('zh-CN', {
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      })
    }

    // 辅助方法
    const getMessageTypeLabel = (type) => {
      const typeMap = {
        system: '系统通知',
        sports: '赛事公告',
        score: '成绩通知',
        schedule: '赛程提醒',
        urgent: '紧急通知'
      }
      return typeMap[type] || type
    }

    const getMessageTypeTagType = (type) => {
      const typeMap = {
        system: '',
        sports: 'success',
        score: 'warning',
        schedule: 'info',
        urgent: 'danger'
      }
      return typeMap[type] || ''
    }

    const getPriorityLabel = (priority) => {
      const priorityMap = {
        low: '低',
        medium: '中',
        high: '高',
        urgent: '紧急'
      }
      return priorityMap[priority] || priority
    }

    const getPriorityTagType = (priority) => {
      const priorityMap = {
        low: 'info',
        medium: '',
        high: 'warning',
        urgent: 'danger'
      }
      return priorityMap[priority] || ''
    }

    const getPushTypeLabel = (type) => {
      const typeMap = {
        app: 'APP推送',
        sms: '短信通知',
        email: '邮件通知',
        wechat: '微信通知'
      }
      return typeMap[type] || type
    }

    const getPushStatusLabel = (status) => {
      const statusMap = {
        success: '推送成功',
        failed: '推送失败',
        pending: '等待推送',
        cancelled: '已取消'
      }
      return statusMap[status] || status
    }

    const getPushStatusTagType = (status) => {
      const statusMap = {
        success: 'success',
        failed: 'danger',
        pending: 'warning',
        cancelled: 'info'
      }
      return statusMap[status] || ''
    }

    return {
      // 响应式数据
      pushing,
      historyLoading,
      templateLoading,
      pushHistoryList,
      templateList,
      selectedTemplates,
      currentPushDetail,
      statistics,
      pushForm,

      // WebSocket 相关数据
      wsConnected,
      activeRecipientTab,
      selectedRoles,
      selectedUsers,
      selectedDepartments,
      selectedRecipients,
      userSearchKeyword,
      roleList,
      userList,
      departmentList,
      historyPagination,
      historySearchForm,
      previewDialogVisible,
      templateDialogVisible,
      pushDetailDialogVisible,

      // 表单引用
      pushFormRef,
      historySearchFormRef,

      // 表单验证规则
      pushFormRules,

      // 计算属性
      checkAllRole,
      isIndeterminateRole,
      checkAllUser,
      isIndeterminateUser,
      checkAllDept,
      isIndeterminateDept,
      filteredUserList,

      // 方法
      loadStatistics,
      loadPushHistory,
      loadTemplates,
      updateSelectedRecipients,
      handleCheckAllRole,
      handleCheckAllUser,
      handleCheckAllDept,
      handleRoleChange,
      handleUserChange,
      handleDepartmentChange,
      handleTabClick,
      handleUserSearch,
      refreshRecipients,
      removeRecipient,
      handlePushMessage,
      resetPushForm,
      testPush,
      showPreviewDialog,
      showTemplateDialog,
      handleTemplateSelection,
      applyTemplate,
      editTemplate,
      deleteTemplate,
      batchDeleteTemplates,
      showAddTemplateDialog,
      searchHistory,
      resetHistorySearch,
      handleHistorySizeChange,
      handleHistoryCurrentChange,
      viewPushDetail,
      cancelPush,
      retryPush,
      exportHistory,
      disabledDate,
      formatTime,

      // 辅助方法
      getMessageTypeLabel,
      getMessageTypeTagType,
      getPriorityLabel,
      getPriorityTagType,
      getPushTypeLabel,
      getPushStatusLabel,
      getPushStatusTagType
    }
  }
}
</script>

<style lang="scss" scoped>
.message-push {
  padding: 20px;

  .breadcrumb {
    margin-bottom: 20px;
  }

  .ws-status-indicator {
    position: fixed;
    top: 80px;
    right: 30px;
    z-index: 1000;

    .status-dot {
      display: flex;
      align-items: center;
      padding: 8px 16px;
      border-radius: 20px;
      font-size: 12px;
      font-weight: 500;
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
      transition: all 0.3s ease;
      cursor: pointer;

      &.connected {
        background-color: #f0f9ff;
        color: #1890ff;
        border: 1px solid #91d5ff;

        &::before {
          content: '';
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: #52c41a;
          margin-right: 8px;
          animation: pulse 2s infinite;
        }
      }

      &.disconnected {
        background-color: #fff2f0;
        color: #ff4d4f;
        border: 1px solid #ffccc7;

        &::before {
          content: '';
          width: 8px;
          height: 8px;
          border-radius: 50%;
          background-color: #ff4d4f;
          margin-right: 8px;
        }
      }

      .status-text {
        white-space: nowrap;
      }

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
      }
    }
  }

  @keyframes pulse {
    0% {
      box-shadow: 0 0 0 0 rgba(82, 196, 26, 0.7);
    }
    70% {
      box-shadow: 0 0 0 10px rgba(82, 196, 26, 0);
    }
    100% {
      box-shadow: 0 0 0 0 rgba(82, 196, 26, 0);
    }
  }

  .statistics-cards {
    margin-bottom: 20px;

    .stat-card {
      .stat-item {
        display: flex;
        align-items: center;

        .stat-icon {
          width: 60px;
          height: 60px;
          border-radius: 50%;
          display: flex;
          align-items: center;
          justify-content: center;
          margin-right: 15px;

          .el-icon {
            font-size: 28px;
            color: white;
          }
        }

        .stat-content {
          flex: 1;

          .stat-value {
            font-size: 28px;
            font-weight: bold;
            color: #303133;
            line-height: 1;
          }

          .stat-label {
            font-size: 14px;
            color: #909399;
            margin-top: 5px;
          }
        }
      }
    }
  }

  .main-content {
    margin-bottom: 20px;

    .push-form-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }
    }

    .recipient-card {
      .card-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
      }

      .role-selection,
      .user-selection,
      .department-selection {
        .role-item,
        .user-item,
        .dept-item {
          margin-bottom: 10px;
          padding: 8px;
          border-radius: 4px;
          transition: background-color 0.3s;

          &:hover {
            background-color: #f5f7fa;
          }

          .role-info,
          .dept-info {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .role-count,
            .dept-count {
              color: #909399;
              font-size: 12px;
            }
          }

          .user-info {
            display: flex;
            align-items: center;

            .user-details {
              margin-left: 10px;

              .user-name {
                font-weight: 500;
              }

              .user-role {
                font-size: 12px;
                color: #909399;
              }
            }
          }
        }
      }

      .user-selection {
        .search-user {
          margin-bottom: 10px;
        }

        .user-list {
          max-height: 300px;
          overflow-y: auto;
        }
      }

      .selected-recipients {
        margin-top: 15px;

        .recipient-tag {
          margin: 5px 5px 5px 0;
        }
      }
    }
  }

  .history-card {
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;

      .header-actions {
        display: flex;
        gap: 10px;
      }
    }

    .history-search {
      margin-bottom: 15px;
      padding: 15px;
      background-color: #f8f9fa;
      border-radius: 4px;
    }

    .push-type-tag {
      margin-right: 5px;
    }

    .pagination-wrapper {
      display: flex;
      justify-content: center;
      margin-top: 20px;
    }
  }

  .message-preview {
    .preview-header {
      h3 {
        margin: 0 0 10px 0;
        color: #303133;
      }

      .preview-meta {
        display: flex;
        align-items: center;
        gap: 10px;

        .preview-time {
          color: #909399;
          font-size: 14px;
          margin-left: auto;
        }
      }
    }

    .preview-content {
      min-height: 100px;
      line-height: 1.6;
      white-space: pre-wrap;
    }

    .preview-recipients,
    .preview-push-types {
      h4 {
        margin: 15px 0 10px 0;
        font-size: 14px;
        color: #606266;
      }

      .recipient-list {
        .preview-recipient-tag {
          margin: 3px 3px 3px 0;
        }

        .more-recipients {
          color: #909399;
          font-size: 12px;
          margin-left: 5px;
        }
      }

      .preview-push-type-tag {
        margin: 3px 3px 3px 0;
      }
    }
  }

  .template-management {
    .template-actions {
      margin-bottom: 15px;
      display: flex;
      gap: 10px;
    }
  }

  .push-detail {
    .push-types-detail {
      .push-type-tag {
        margin-right: 5px;
      }
    }

    .push-content {
      white-space: pre-wrap;
      line-height: 1.6;
      max-height: 200px;
      overflow-y: auto;
    }

    .failure-reason {
      color: #f56c6c;
      line-height: 1.6;
    }
  }

  .dialog-footer {
    display: flex;
    justify-content: flex-end;
    gap: 10px;
  }
}

// 响应式设计
@media (max-width: 1200px) {
  .message-push {
    .main-content {
      .el-col {
        margin-bottom: 20px;
      }
    }
  }
}

@media (max-width: 768px) {
  .message-push {
    padding: 10px;

    .ws-status-indicator {
      top: 70px;
      right: 15px;

      .status-dot {
        padding: 6px 12px;
        font-size: 11px;
      }
    }

    .statistics-cards {
      .el-col {
        margin-bottom: 10px;
      }
    }

    .card-header {
      flex-direction: column;
      gap: 10px;
      align-items: flex-start !important;
    }

    .history-search {
      .el-form-item {
        margin-bottom: 10px;
      }
    }
  }
}
</style>